//
//  SportCollectionViewController.m
//  StormWatch
//
//  Created by 王岩 on 2024/8/30.
//

#import "SportViewController.h"
#import "SportCollectionViewCell.h"
#import "ZZCircleProgress.h"
#import "SportDetailViewController.h"
#import "FRIDefine.h"


@interface SportViewController ()<UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout>

@property (nonatomic, strong) UICollectionView * collectionView;
@property (nonatomic, strong) NSArray * dataArr, *normalImgArr, *imageArr;
@property (nonatomic, assign) unsigned long stepData;
@property (nonatomic, assign) BOOL bleConnected;

@property (nonatomic, strong) UIView * topView, *connecePoint;
@property (nonatomic, strong) UIImageView * stepImage, *caloImage;
@property (nonatomic, strong) UILabel *connectLab, * stepLab, *currentStepLab, *currentCaloLab, * tipsLab, *stepValueLab, *caloValueLab, *titleLab;
@property (nonatomic, strong) CAGradientLayer * layer;
@property (nonatomic, strong) ZZCircleProgress * circleProgressView;

@end

@implementation SportViewController


- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:YES animated:animated];
    [self  readData];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(updateTheme) name:@"k_change_theme" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(bleCancelConnect) name:FRINotificationAtDidDisconnectPeripheral object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(readData) name:@"appDidBecomeActive" object:nil];

    [self initData];
   
    self.bleConnected = NO;
    [self initUI];
    [self updateTheme];
    // Do any additional setup after loading the view.
}


- (void)initData {
    
    
    self.dataArr = @[SWString(@"Running"),SWString(@"Riding"),SWString(@"Tennis"),SWString(@"Climbing"),SWString(@"Walking"),SWString(@"Basketball"),SWString(@"Soccer"),SWString(@"Yoga"),SWString(@"Workout")];
    
    
    NSString * type = @"";
    switch (ThemeManager.sharedInstance.themeValue) {
       
        case Theme_Red:
        {
            type = @"red";
        }
            break;
        case Theme_Purple:
        {
            type = @"purple";
        }
            break;
        case Theme_LightBlue:
        {
            type = @"lblue";
        }
            break; 
        case Theme_Green:
        {
            type = @"green";
        }
            break; 
        case Theme_DarkBlue:
        {
            type = @"dblue";
        }
            break; 
        case Theme_Black:
        {
            type = @"black";
        }
            break;
        default:
            self.imageArr = @[@"icon_sport_run",@"icon_sport_bike",@"icon_sport_tennis",@"icon_sport_mount",@"icon_sport_step",@"icon_sport_basketball",@"icon_sport_football",@"icon_sport_yoga",@"icon_sport_free"];
            self.normalImgArr = @[@"icon_sport_run_gray",@"icon_sport_bike_gray",@"icon_sport_tennis_gray",@"icon_sport_mount_gray",@"icon_sport_step_gray",@"icon_sport_basketball_gray",@"icon_sport_football_gray",@"icon_sport_yoga_gray",@"icon_sport_free_gray"];
            
            return;
            break;
    }
   
    self.imageArr = @[[NSString stringWithFormat:@"icon_sport_run_%@",type],[NSString stringWithFormat:@"icon_sport_bike_%@",type],[NSString stringWithFormat:@"icon_sport_tennis_%@",type],[NSString stringWithFormat:@"icon_sport_mount_%@",type],[NSString stringWithFormat:@"icon_sport_step_%@",type],[NSString stringWithFormat:@"icon_sport_basketball_%@",type],[NSString stringWithFormat:@"icon_sport_football_%@",type],[NSString stringWithFormat:@"icon_sport_yoga_%@",type],[NSString stringWithFormat:@"icon_sport_free_%@",type]];
    self.normalImgArr = @[[NSString stringWithFormat:@"icon_sport_run_gray_%@",type],[NSString stringWithFormat:@"icon_sport_bike_gray_%@",type],[NSString stringWithFormat:@"icon_sport_tennis_gray_%@",type],[NSString stringWithFormat:@"icon_sport_mount_gray_%@",type],[NSString stringWithFormat:@"icon_sport_step_gray_%@",type],[NSString stringWithFormat:@"icon_sport_basketball_gray_%@",type],[NSString stringWithFormat:@"icon_sport_football_gray_%@",type],[NSString stringWithFormat:@"icon_sport_yoga_gray_%@",type],[NSString stringWithFormat:@"icon_sport_free_gray_%@",type]];
}

- (void)initUI {
    [self connectLab];
    [self topView];
    [self.view addSubview:self.titleLab];
    [self.view addSubview:self.collectionView];
    [self.collectionView mas_makeConstraints:^(MASConstraintMaker *make) {
        kMakeLV(15);kMakeRV(-15);
        kMakeT(self.titleLab.mas_bottom).offset(10);
        kMakeBV(-kTabBarHeight);
    }];
}

- (void)readData {

    if ([FRQBluetoothManager shareManager].ready) {
        [[StormCommandTool sharedInstance] readRealTimeData:^(BOOL success, unsigned long stepData, unsigned long caloriesData, unsigned long distanceData, unsigned long heartRateData, unsigned long electricData) {
            self.stepData = stepData;
            [self updateCircleValue];
            self.stepValueLab.text = [NSString stringWithFormat:@"%lu", stepData];
            self.caloValueLab.text = [NSString stringWithFormat:@"%.2fkCal", caloriesData / 1000.0];
        }];
        [self.collectionView reloadData];
        [self updateData];
    }else {
        [self bleCancelConnect];
    }

}

- (void)updateTheme {
    
    [self initData];
    
    self.titleLab.text = SWString(@"Sport data");
    self.tipsLab.text = SWString(@"Come on! You can do better!！");
    self.currentCaloLab.text = SWString(@"Current calories");
    self.currentStepLab.text = SWString(@"Current step");
    self.stepLab.text = SWString(@"Step");
    
    self.connectLab.text = SWString(@"Watch not connected");
    
    self.view.backgroundColor = [ThemeManager sharedInstance].themeColor;
    self.titleLab.textColor = ThemeManager.sharedInstance.textColor;
    self.layer.colors = [ThemeManager sharedInstance].themeValue == Theme_Default? @[(id)S_HexColor(@"#041A72").CGColor, (id)S_HexColor(@"#041A72").CGColor] : [ThemeManager sharedInstance].gradientColors;
    
    if (ThemeManager.sharedInstance.themeValue == Theme_Default) {
        self.stepLab.textColor = self.stepValueLab.textColor = self.currentCaloLab.textColor = self.currentStepLab.textColor = self.caloValueLab.textColor = self.tipsLab.textColor = [UIColor whiteColor];
    }else {
        self.stepLab.textColor = self.stepValueLab.textColor = self.currentCaloLab.textColor = self.currentStepLab.textColor = self.caloValueLab.textColor = self.tipsLab.textColor = [ThemeManager  sharedInstance].textColor;
    }
    
    self.circleProgressView.pathBackColor = [ThemeManager sharedInstance].circleBackColor;
    self.circleProgressView.pathFillColor = [ThemeManager sharedInstance].circleFillColor;
    
    [self.collectionView reloadData];
    
    [self updateCircleValue];
}

- (void)updateCircleValue {
    long long  target = [[[NSUserDefaults standardUserDefaults] valueForKey:@"Storm_steptarget"] longLongValue];

    NSString * num = [NSString stringWithFormat:@"\n%lld",target];
    self.circleProgressView.progressLabel.attributedText = [SWTool attS1:SWString(@"Goal") s2:num f1:S_font(14) c1:ThemeManager.sharedInstance.themeValue == Theme_Default?[UIColor whiteColor]:[ThemeManager sharedInstance].textColor f2:S_bfont(16) c2:ThemeManager.sharedInstance.themeValue == Theme_Default?[UIColor whiteColor]:[ThemeManager sharedInstance].textColor];
    
    if (target > 0) {
        self.circleProgressView.progress = (float)self.stepData / (float)target;
    }else {
        self.circleProgressView.progress = 0;
    }
}

/// 蓝牙连接
- (void)updateData {
    self.topView.y =  kStatusBarHeight;
    self.bleConnected = YES;
}

/// 蓝牙断开
- (void)bleCancelConnect {
    self.topView.y =  kStatusBarHeight + 30;
    self.bleConnected = NO;
    self.stepData = 0;
    NSString * num = [NSString stringWithFormat:@"\n%lu",self.stepData];
    self.circleProgressView.progressLabel.attributedText = [SWTool attS1:SWString(@"Goal") s2:num f1:S_font(14) c1:ThemeManager.sharedInstance.themeValue == Theme_Default?[UIColor whiteColor]:[ThemeManager sharedInstance].textColor f2:S_bfont(16) c2:ThemeManager.sharedInstance.themeValue == Theme_Default?[UIColor whiteColor]:[ThemeManager sharedInstance].textColor];
    self.circleProgressView.progress = 0;
    _stepValueLab.text = @"0";
    _caloValueLab.text = @"0.00kCal";
    [self.collectionView reloadData];
}

#pragma mark <UICollectionViewDataSource>
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return self.dataArr.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    SportCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"SportCollectionViewCell" forIndexPath:indexPath];
    cell.nameLab.textColor = ThemeManager.sharedInstance.textColor;
    cell.nameLab.text = self.dataArr[indexPath.row];
    if (self.bleConnected) {
        cell.iconView.image = S_imageNamed(self.imageArr[indexPath.row]);
    }else {
        cell.iconView.image =  S_imageNamed(self.normalImgArr[indexPath.row]) ;
    }
   
    
    return cell;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    SportDetailViewController * vc = [[SportDetailViewController alloc] init];
    vc.type = indexPath.row;
    vc.noDataImageName = self.normalImgArr[indexPath.row];
    vc.name = self.dataArr[indexPath.row];
    vc.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:vc
                                         animated:YES];
}

- (UICollectionView *)collectionView {
    if (!_collectionView) {
        UICollectionViewFlowLayout * layout = [[UICollectionViewFlowLayout alloc] init];
        layout.minimumLineSpacing = 15;
        layout.minimumInteritemSpacing = 15;
        layout.itemSize = CGSizeMake((kScreenWidth - 45) / 2, (kScreenWidth - 35) / 2);
        _collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(15, kNavigationBarHeight, kScreenWidth - 30, kScreenHeight - kNavigationBarHeight - kTabBarHeight) collectionViewLayout:layout];
        _collectionView.delegate = self;
        _collectionView.dataSource = self;
        _collectionView.backgroundColor = [UIColor clearColor];
        [_collectionView registerNib:[UINib nibWithNibName:@"SportCollectionViewCell" bundle:nil] forCellWithReuseIdentifier:@"SportCollectionViewCell"];
        
    }
    return _collectionView;
}

- (UILabel *)connectLab {
    if (!_connectLab) {
        _connecePoint = [[UIView alloc] initWithFrame:CGRectMake(15, kStatusBarHeight + 12, 6, 6)];
        _connecePoint.layer.cornerRadius = 3;
        _connecePoint.backgroundColor = [UIColor redColor];
        [self.view addSubview:_connecePoint];
        
        _connectLab = [SWInitializer jy_initLabelWithText:SWString(@"Watch not connected") textColor:S_HexColor(@"0x666666") font:S_font(14) bgColor:[UIColor clearColor] on:self.view layout:^(MASConstraintMaker * _Nonnull make) {
            kMakeL(self.connecePoint.mas_right).offset(10);
            kMakeHV(30);
            kMakeTV(kStatusBarHeight);
        }];
    }
    return _connectLab;
}

- (UIView *)topView {
    if (!_topView) {
        _topView = [[UIView alloc] initWithFrame:CGRectMake(15, kStatusBarHeight + 30, kScreenWidth - 30, 140)];
        _topView.layer.cornerRadius =  10;
        _topView.layer.masksToBounds =  YES;
        [self.view addSubview:_topView];
        
        CAGradientLayer * layer = [[CAGradientLayer alloc] init];
        layer.frame = _topView.bounds;
        layer.startPoint = CGPointMake(0, 1 );
        layer.endPoint = CGPointMake(0, 0);
        layer.colors = [ThemeManager sharedInstance].gradientColors;
        _layer = layer;
        [_topView.layer insertSublayer:layer atIndex:0];
        
        _stepLab = [SWInitializer jy_initLabelWithText:SWString(@"Step") textColor:[UIColor whiteColor] font:[UIFont systemFontOfSize:18 weight:UIFontWeightSemibold] bgColor:[UIColor clearColor] on:_topView layout:^(MASConstraintMaker * _Nonnull make) {
            kMakeLV(10);kMakeTV(10);
            kMakeHV(30);
        }];
        
        _stepImage = [SWInitializer jy_initImageViewWithImage:S_imageNamed(@"icon_sport_cal") on:_topView layout:^(MASConstraintMaker * _Nonnull make) {
            kMakeWHV(16, 16);
            kMakeLV(10);kMakeT(self.stepLab.mas_bottom).offset(8);
        }];
        _caloImage = [SWInitializer jy_initImageViewWithImage:S_imageNamed(@"icon_sport_step222") on:_topView layout:^(MASConstraintMaker * _Nonnull make) {
            kMakeWHV(16, 16);
            kMakeLV(10);kMakeT(self.stepImage.mas_bottom).offset(10);
        }];
        
        _currentStepLab = [SWInitializer jy_initLabelWithText:SWString(@"Current step") textColor:[ThemeManager sharedInstance].textColor font:S_font(14) bgColor:[UIColor clearColor] on:_topView layout:^(MASConstraintMaker * _Nonnull make) {
            kMakeL(self.stepImage.mas_right).offset(10);
            kMakeCenterY(self.stepImage.mas_centerY);
        }];
        _currentCaloLab = [SWInitializer jy_initLabelWithText:SWString(@"Current calories") textColor:[ThemeManager sharedInstance].textColor font:S_font(14) bgColor:[UIColor clearColor] on:_topView layout:^(MASConstraintMaker * _Nonnull make) {
            kMakeL(self.caloImage.mas_right).offset(10);
            kMakeCenterY(self.caloImage.mas_centerY);
        }];
        
        _stepValueLab = [SWInitializer jy_initLabelWithText:@"0" textColor:[ThemeManager sharedInstance].textColor font:S_bfont(14) bgColor:[UIColor clearColor] on:_topView layout:^(MASConstraintMaker * _Nonnull make) {
            kMakeL(self.currentStepLab.mas_right).offset(2);
            kMakeCenterY(self.stepImage.mas_centerY);
        }];
        
        _caloValueLab = [SWInitializer jy_initLabelWithText:@"0.00kCal" textColor:[ThemeManager sharedInstance].textColor font:S_bfont(14) bgColor:[UIColor clearColor] on:_topView layout:^(MASConstraintMaker * _Nonnull make) {
            kMakeL(self.currentCaloLab.mas_right).offset(2);
            kMakeCenterY(self.caloImage.mas_centerY);
        }];
        
        _tipsLab = [SWInitializer jy_initLabelWithText:SWString(@"Come on! You can do better!！") textColor:[ThemeManager sharedInstance].textColor font:S_bfont(14) bgColor:[UIColor clearColor] on:_topView layout:^(MASConstraintMaker * _Nonnull make) {
            kMakeL(self.stepImage.mas_left);
            kMakeT(self.caloImage.mas_bottom).offset(15);
        }];
     
        [_topView addSubview:self.circleProgressView];
        [_circleProgressView mas_makeConstraints:^(MASConstraintMaker *make) {
            kMakeRV(-10);
            kMakeCenterYV(0);
            kMakeWHV(100, 100);
        }];
        
    }
    return _topView;
}

- (ZZCircleProgress *)circleProgressView {
    if (!_circleProgressView) {
        _circleProgressView = [[ZZCircleProgress alloc] initWithFrame:CGRectMake(0, 0, 110, 110) pathBackColor:[ThemeManager sharedInstance].circleBackColor pathFillColor:[ThemeManager sharedInstance].circleFillColor startAngle:-90 strokeWidth:3];
        _circleProgressView.reduceAngle = 0;//整合进度条缺少30度
    //    self.circleProgressView.pointImage.image = [UIImage imageNamed:@"test"];//设置小圆点图片
        _circleProgressView.duration = 1.0;//动画时长。默认为1.5
        _circleProgressView.showProgressText = YES;//是否显示默认进度文本。默认为YES
        _circleProgressView.increaseFromLast = NO;//进度条动画是否从上次进度开始动画。默认为NO
        _circleProgressView.startAngle = -90;
    
        
        _circleProgressView.showPoint = NO;//是否显示默认小圆点。默认为YES·
        
        _circleProgressView.progressLabel.numberOfLines = 2;
        
        NSString * num = [NSString stringWithFormat:@"%@\n",SWString(@"Goal")];
        _circleProgressView.progressLabel.attributedText = [SWTool attS1:num s2:@"0" f1:S_font(14) c1:[ThemeManager sharedInstance].textColor f2:S_bfont(16) c2:[ThemeManager sharedInstance].textColor];
        
        _circleProgressView.progress = 0;
            
    }
    return _circleProgressView;
}

- (UILabel *)titleLab {
    if (!_titleLab) {
        _titleLab = [SWInitializer jy_initLabelWithText:SWString(@"Sport data") textColor:ThemeManager.sharedInstance.textColor font:U_sfont(18) bgColor:[UIColor clearColor] on:self.view layout:^(MASConstraintMaker * _Nonnull make) {
            kMakeL(self.topView.mas_left);
            kMakeT(self.topView.mas_bottom).offset(10);
            kMakeHV(20);
        }];
    }
    return _titleLab;
}

@end
